const app = getApp()
import {
  judgeIsAuth
} from '../../utils/auth'
import {
  getRandomIndex
} from '../../utils/util'
import {
  getProduct,
  addCart
} from '../../api/user'
import {
  LIDONG_WINE_ID,
  LIDONG_WINE_MOQ
} from '../../assets/constant/index'

// 盲盒家电套餐图片
const MHJDIMAGES = ['https://staticmall.joymew.com//admin-upload/2024/3/18/14/CrjbhC','https://staticmall.joymew.com//admin-upload/2024/3/18/14/Z3fKyB','https://staticmall.joymew.com//admin-upload/2024/3/18/14/J82p4W',' https://ustatic.hudongmiao.com/%20joymewApp/dd.png','https://ustatic.hudongmiao.com/%20joymewApp/de.png'];
// 盲盒家电抽奖商品id
const MHJDID = '1564173144465461250'
Page({
  data: {
    pb: 0,
    addressId: '',
    homeText: '',
    currentSwiper: 0,
    currentTab: 0,
    bannerList: [],
    productId: null,
    picUrls: [],
    price: 0,
    name: '',
    saleCount: 0,
    stockCount: 0,
    detail: '',
    spcesInfo: [],
    specCount: 1,
    spceVisible: false,
    activeSpec: '',
    productId: '',
    authDialogVisible: false, // 控制”获取头像昵称“弹窗的显示/隐藏
    spcesImages: [], // 套餐图片列表
    activeSpcesImage: '', // 当前展示的套餐图片
  },
  onLoad(options) {
    const {
      productId
    } = options
    if (productId) {
      this.setData({
        productId
      })
    }
  },

  onShow() {
    if(this.inImagePreview) {
      this.inImagePreview = false;
      return;
    }
    // 设置底部安全距离
    this.setData({
      pb: app.globalData.app.paddingBottom
    })
    // 设置左上角返回按钮的文案
    if (getCurrentPages().length === 1) {
      this.setData({
        homeText: '主页'
      })
    } else {
      this.setData({
        homeText: '返回'
      })
    }
    // 获取商品信息
    this.initProduct()
    // 根据商品Id设置该商品的起订数量
    this.setMOQByProductId();
  },
  onClickLeft() {
    if (getCurrentPages().length === 1) {
      wx.switchTab({
        url: '/pages/index/index',
      })
    } else {
      wx.navigateBack({
        delta: -1,
      })
    }
  },
  onSwiperChange(e) {
    // console.log(e)
    this.setData({
      currentSwiper: e.detail.current
    })
  },
  onTabChange(e) {
    // console.log(e)
    this.setData({
      currentTab: e.detail.index
    })
  },
  initProduct() {
    const {
      productId
    } = this.data
    getProduct({
        productId
      }).then(res => {
        console.log('*************', res)
        const {
          product,
          spcesInfo
        } = res.data
        if (product) {
          const {
            pic,
            price,
            name,
            saleCount,
            stockCount,
            detail,
            shareDesc
          } = product

          // if(pic){
          let bannerList = pic.split(',')
          // }
          // console.log(detail)
          // let handleDetail = detail;
          // handleDetail = detail.replace(/<img/g, `<img style="width:100%;" class="aw"`)
          // console.log(handleDetail)
          // wx.aldVisit({
          //   category:'一般商品',  // 改字段为商品类别（必传） String 最多支持 32 个字符
          //   id: productId,   // 商品唯一id(必传)   String||Number 
          //   name: name.substr(0,32),   // 商品名称（必传）  String  最多支持 32 个字符
          // })
          this.setData({
            bannerList,
            activeSpcesImage: bannerList[0],
            price,
            name,
            shareDesc,
            saleCount,
            stockCount,
            detail
          })
        } else {
          wx.showToast({
            title: '商品信息获取失败！点击右上角重新进入小程序!',
            icon: 'none',
            duration: 10000,
          })
          // 非预期情况上报信息
          this.reportEvent()
        }
        if (spcesInfo) {
          let finallSpcesInfo = spcesInfo || []
          console.log('spcesInfo', finallSpcesInfo, res.data.spcesInfo)
          const spcesImages = productId === MHJDID ? MHJDIMAGES : [];
          this.setData({
            spcesInfo: finallSpcesInfo,
            spcesImages,
          });
        }
      })
      .catch(err => {
        console.log(err)
      })
  },

  async addCart() {
    // 如果缓存中没有头像昵称则唤起”获取头像昵称“弹窗
    const auth = await judgeIsAuth()
    if (!auth) {
      // wx.showToast({
      //   title: '授权失败',
      //   icon: 'none'
      // })
      this.setData({
        authDialogVisible: true
      });
      return;
    }


    const {
      productId
    } = this.data
    addCart({
      productId
    }).then(res => {
      console.log(res)
      wx.showToast({
        title: '添加成功',
        icon: 'none'
      })
      // setTimeout(() => {
      //   wx.switchTab({
      //     url: '/pages/cart/cart',
      //   })
      // }, 2000);
    }).catch(err => {
      console.log(err)

      wx.showToast({
        title: '添加失败',
        icon: 'none'
      })
    })
  },
  async buyGood() {
    // 如果缓存中没有头像昵称则唤起”获取头像昵称“弹窗
    const auth = await judgeIsAuth()
    if (!auth) {
      wx.showToast({
        title: '授权失败',
        icon: 'none'
      })
      // this.setData({
      //   authDialogVisible: true
      // });
      return;
    }

    const {
      name,
      bannerList,
      price,
      productId,
      spcesInfo,
      activeSpec,
      specCount
    } = this.data
    let jsonKey = String(productId)
    let params = {
      jsonKey
    }
    if (spcesInfo.length > 0 && activeSpec === '') {
      this.setData({
        spceVisible: true,
      })

      return;

    } else if (spcesInfo.length > 0 && activeSpec !== '') {
      let targetSpec = spcesInfo[activeSpec]
      console.log(targetSpec)
      if (Number(targetSpec.stockCount) <= 0) {
        wx.showToast({
          title: '该套餐库存不足',
          icon: 'none'
        })

        return;
      }
      params.jsonKey = `${productId}_${targetSpec.specsId}`

      if (Number(specCount) <= 0) {
        wx.showToast({
          title: '商品数不能为0',
          icon: 'none'
        })
        return;
      }
      params.jsonVal = JSON.stringify({
        [params.jsonKey]: String(specCount) || '1'
      })
    }
    // console.log(params)
    // console.log('可付款')
    wx.navigateTo({
      url: `/pages/order/detail/detail`,
      success: (res) => {
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          name,
          bannerList,
          price,
          params,
          specCount,
          productId,
          spcesInfo,
          activeSpec,
        })
      }
    })
  },
  subtractCount() {
    const {
      specCount,
      activeSpec
    } = this.data
    if (activeSpec === '') {
      wx.showToast({
        title: '请先选择套餐',
        icon: 'none'
      })
      return;
    }
    // const tenantId = wx.getStorageSync('tenantId')
    // 礼东酒起订数量起订数量不能小于30
    if (this.data.productId === LIDONG_WINE_ID && Number(specCount) <= 30) {
      wx.showToast({
        title: '起订数量是30!',
        icon: 'none'
      })
      return;
    }
    if (Number(specCount) === 1) {
      wx.showToast({
        title: '不能低于起送数量',
        icon: 'none'
      })
      return;
    }
    this.setData({
      specCount: Number(specCount) - 1
    })
  },
  plusCount() {
    const {
      specCount,
      spcesInfo,
      activeSpec
    } = this.data
    if (activeSpec === '') {
      wx.showToast({
        title: '请先选择套餐',
        icon: 'none'
      })
      return;
    }
    let max = Infinity
    if (activeSpec !== '') {
      max = Number(spcesInfo[activeSpec].stockCount)
    }
    if (Number(specCount) >= max) {
      wx.showToast({
        title: '数量不能大于库存',
        icon: 'none'
      })
      return;
    }
    this.setData({
      specCount: Number(specCount) + 1
    })
    // if(Number(specCount) <= ){

    // }
  },
  sureIt() {

    const {
      activeSpec
    } = this.data


    if (String(activeSpec).trim() === '') {
      wx.showToast({
        title: '请选择规格',
        icon: 'none'
      })
      return
    }
    this.buyGood()
  },
  chooseIt(e) {
    console.log(e)
    const {
      activeSpec,
      specCount
    } = this.data
    const {
      index,
      count
    } = e.currentTarget.dataset
    // if(Number(count)<=0){
    //   wx.showToast({
    //     title: '该规格库存不足',
    //     icon: 'none'
    //   })
    //   return ;
    // }
    if (index === activeSpec) {
      this.setData({
        activeSpec: '',
        activeSpcesImage: this.data.bannerList[0]
      })
    } else {
      this.setData({
        activeSpec: index,
        specCount: Number(specCount) > Number(count) ? 1 : Number(specCount),
        activeSpcesImage: this.data.productId === MHJDID ? MHJDIMAGES[index] : this.data.bannerList[0]
      })
    }
  },
  onClose() {
    this.setData({
      spceVisible: false,
      activeSpec: '',
      activeSpcesImage: this.data.bannerList[0
      
      ]
    })
  },
  // 根据商品Id设置该商品的起订数量
  // 礼东酒起定数量为6
  setMOQByProductId() {
    if (this.data.productId === LIDONG_WINE_ID) {
      this.setData({
        specCount: LIDONG_WINE_MOQ
      })
    }
  },
  onShareAppMessage() {
    const {
      bannerList
    } = this.data
    const targetImg = bannerList[getRandomIndex(0, bannerList.length)]
    const {
      name,
      shareDesc,
      productId
    } = this.data
    const imageUrl = targetImg || ''
    let tenantId = wx.getStorageSync('tenantId')
    let shareId = wx.getStorageSync('shareId')
    let path = '/pages/good/good?a=1';
    if (tenantId) {
      path += `&tenantId=${tenantId}`
    }
    if (shareId) {
      path += `&shareId=${shareId}`
    }
    if (productId) {
      path += `&productId=${productId}`
    }
    console.log(path)
    return {
      title: `${name} -${shareDesc}(${wx.getStorageSync('shop_name')})`,
      imageUrl,
      path,
    }
  },
  // 非预期情况上报信息
  // 调用时机：获取商品详情失败 调用该方法
  // 上报内容：
  // 缓存中的用户id、缓存中的分享者id
  // 缓存中的店铺id、商品id
  reportEvent() {
    let tmpStorageUserId
    const storageUserObj = wx.getStorageSync('user')
    try {
      tmpStorageUserId = storageUserObj.userId
    } catch (err) {
      console.log(err)
    }
    const tmpJsonObj = {
      "storageuserid": tmpStorageUserId,
      "storageshareid": wx.getStorageSync('shareId'),
      "storagetenantid": wx.getStorageSync('tenantId'),
      "productid": this.data.productId,
    }
    app.FrontJS.addUserData('unexpectState', JSON.stringify(tmpJsonObj))
  },
  /**
   * 预览图片
   */
  previewImage(e) {
    const imgPath = e.target.dataset.image;
    this.inImagePreview = true;
    wx.previewImage({
      urls: [imgPath],
    });
  },
})